class <%= class_name %>Controller < ApplicationController
  def index
    <%= name_plural %> = <%= class_name %>.all
    respond_with 200 do
      json <%= name_plural %>.to_json
    end
  end

  def show
    if <%= @name %> = <%= class_name %>.find params["id"]
      respond_with 200 do
        json <%= @name %>.to_json
      end
    else
      results = {status: "not found"}
      respond_with 404 do
        json results.to_json
      end
    end
  end

  def create
    <%= @name %> = <%= class_name %>.new(<%= @name %>_params.validate!)

    if <%= @name %>.valid? && <%= @name %>.save
      respond_with 201 do
        json <%= @name %>.to_json
      end
    else
      results = {status: "invalid"}
      respond_with 422 do
        json results.to_json
      end
    end
  end

  def update
    if <%= @name %> = <%= class_name %>.find(params["id"])
      <%= @name %>.set_attributes(<%= @name %>_params.validate!)
      if <%= @name %>.valid? && <%= @name %>.save
        respond_with 200 do
          json <%= @name %>.to_json
        end
      else
        results = {status: "invalid"}
        respond_with 422 do
          json results.to_json
        end
      end
    else
      results = {status: "not found"}
      respond_with 404 do
        json results.to_json
      end
    end
  end

  def destroy
    if <%= @name %> = <%= class_name %>.find params["id"]
      <%= @name %>.destroy
      respond_with 204 do
        json ""
      end
    else
      results = {status: "not found"}
      respond_with 404 do
        json results.to_json
      end
    end
  end

  def <%= @name %>_params
    params.validation do
      <%- @fields_hash.keys.each do |k| -%>
      required(:<%= k %>, msg: nil, allow_blank: true)
      <%- end -%>
    end
  end
end
